import { globalTool, globalLayer } from '../BQGIS-globalVar'


export function initGraphicLayer(viewer = window.viewer) {
    if (!globalLayer.sightlineLayer) {
        globalLayer.sightlineLayer = new mars3d.layer.GraphicLayer()
        viewer.addLayer(globalLayer.sightlineLayer)
    }
    if (!globalTool.sightline) {
        globalTool.sightline = new mars3d.thing.Sightline()
        viewer.addThing(globalTool.sightline)
        globalTool.sightline.on(mars3d.EventType.end, function (graphic) {
            const position = graphic.position
            setGraphicJD(position)
        })
    }
    return globalLayer.sightlineLayer
}

export function setGraphicJD(position) {
    const graphic = globalLayer.sightlineLayer.getGraphicByAttr('交点', 'name')
    if (graphic) {
        graphic.position = position
    } else {
        globalLayer.sightlineLayer.addGraphic(new mars3d.graphic.PointEntity({
            position,
            hasEdit: false,
            name: '交点',
            style: {
                pixelSize: 15,
                color: "#0000ff",
                label: {
                    text: "与地面的交点",
                    font_size: 18,
                    color: "#ffff00",
                    outline: true,
                    outlineColor: "#0000ff",
                    pixelOffsetY: -20
                }
            }
        }))
    }
}

// 计算与地面焦点
export function analysisIntersection(option) {
    const GCD = globalLayer.sightlineLayer.getGraphicByAttr('观察点', 'name')
    const MBD = globalLayer.sightlineLayer.getGraphicByAttr('目标点', 'name')
    if (GCD && MBD) {
        globalTool.sightline.clear()
        return globalTool.sightline.addAsync(GCD.positionShow, MBD.positionShow, option) 
    }else {
        return Promise.reject()
    }
}

// 设置摄像头位置
export function drawPoint(type) {
    initGraphicLayer()
    const graphic = globalLayer.sightlineLayer.getGraphicByAttr(type, 'name')
    if (graphic) {
        graphic.remove()
    }
    return globalLayer.sightlineLayer.startDraw({
        type: "point",
        name: type,
        style: {
            pixelSize: 20,
            color: "#ffff00",
            label: {
                text: type,
                font_size: 20,
                color: "#00ffff",
                outline: true,
                outlineColor: "#000000",
                pixelOffsetY: -20
            }
        },
        hasEdit: true,
    })
}

// 清除
export function clear() {
    if (globalTool.sightline) {
        globalTool.sightline.clear()
    }
    if (globalLayer.sightlineLayer) {
        globalLayer.sightlineLayer.clear()
    }
}